/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/idenger">idenger</a> All rights reserved.
 */
package com.idenger.modules.edu.web.user;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.idenger.modules.edu.entity.common.BaseResponseMsg;
import com.idenger.modules.edu.entity.course.EduCourse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.idenger.common.config.Global;
import com.idenger.common.persistence.Page;
import com.idenger.common.web.BaseController;
import com.idenger.common.utils.StringUtils;
import com.idenger.common.utils.excel.ExportExcel;
import com.idenger.common.utils.excel.ImportExcel;
import com.idenger.modules.edu.entity.common.ResponseMsg;
import com.idenger.modules.edu.entity.enroll.EduEnroll;
import com.idenger.modules.edu.entity.enrolldetails.EduEnrollDetails;
import com.idenger.modules.edu.entity.order.EduOrder;
import com.idenger.modules.edu.entity.project.EduProject;
import com.idenger.modules.edu.entity.user.EduUser;
import com.idenger.modules.edu.entity.userextra.EduUserExtra;
import com.idenger.modules.edu.service.course.EduCourseService;
import com.idenger.modules.edu.service.enroll.EduEnrollService;
import com.idenger.modules.edu.service.enrolldetails.EduEnrollDetailsService;
import com.idenger.modules.edu.service.order.EduOrderService;
import com.idenger.modules.edu.service.project.EduProjectService;
import com.idenger.modules.edu.service.user.EduUserService;
import com.idenger.modules.edu.service.userextra.EduUserExtraService;
import com.idenger.modules.edu.web.comm.Constant;
import com.idenger.modules.edu.web.utils.IdNumber;
import com.idenger.modules.edu.web.utils.MakeOrderNum;

import aj.org.objectweb.asm.Label;

/**
 * 用户Controller
 * @author 兰正军
 * @version 2017-12-01
 */
@Controller
@RequestMapping(value = "${adminPath}/edu/user/eduUser")
public class EduUserController extends BaseController { 

	@Autowired
	private EduUserService eduUserService;
	@Autowired
	private EduUserExtraService eduUserExtraService;
	@Autowired
	private EduOrderService eduOrderService;
	@Autowired
	private EduEnrollService eduEnrollService;
	@Autowired
	private EduEnrollDetailsService eduEnrollDetailsService;
	@Autowired
	private EduCourseService eduCourseService;
	@Autowired
	private EduProjectService eduProjectService;
	
	@ModelAttribute
	public EduUser get(@RequestParam(required=false) String id) {
		EduUser entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eduUserService.get(id);
		}
		if (entity == null){
			entity = new EduUser();
		}
		return entity;
	}
	
	@RequiresPermissions("edu:user:eduUser:view")
	@RequestMapping(value = {"list", ""})
	public String list(EduUser eduUser, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<EduUser> page = eduUserService.findListByDetails(new Page<EduUser>(request, response), eduUser); 
		model.addAttribute("queryCriteria",eduUser.getQueryCriteria());
		model.addAttribute("startDate",eduUser.getStartDate());
		model.addAttribute("endDate",eduUser.getEndDate());
		model.addAttribute("page", page);
		return "modules/edu/user/eduUserList";
	}
	

	@RequiresPermissions("edu:user:eduUser:view")
	@RequestMapping(value = "form")
	public String form(EduUser eduUser, Model model) {
		model.addAttribute("eduUser", eduUser);
		return "modules/edu/user/eduUserForm";
	}
	
	/***
	 * 重置密码
	 * @param eduUser
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "resetPassword")
	public String resetPassword(EduUser eduUser, Model model, RedirectAttributes redirectAttributes){
		eduUser.setPassword(DigestUtils.md5Hex(Constant.UESER_DEFAULT_PASSWRRD));
		eduUserService.save(eduUser);
		addMessage(redirectAttributes, "保存用户成功");
		return "redirect:"+Global.getAdminPath()+"/edu/user/eduUser/?repage";
	}
	
	@RequiresPermissions("edu:user:eduUser:view")
	@RequestMapping(value = "get")
	public String get(EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model) {
		BaseResponseMsg baseResponseMsg;
		EduUserExtra eduUserExtra = eduUserExtraService.getByUserId(eduUser.getId());
		//查询该用户下购买的项目
		List<EduProject> eduProjects = findProjectListByuserId(eduUser);
		EduCourse course = new EduCourse();
		course.setEduUser(eduUser);
		List<EduCourse> courseList = eduCourseService.listByForEnrollAndUserId(course);
		List<EduCourse> proveList = eduCourseService.creditCertificateNotPage(course);
		
		Map map = new HashMap<>();
		map.put("eduUser", eduUser);
		map.put("eduUserExtra", eduUserExtra);
		map.put("eduProjectList", eduProjects);
		map.put("courseList", courseList);
		map.put("proveList",proveList);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(map);
		return renderString(response, baseResponseMsg);
	}
	
	public List<EduProject> findProjectListByuserId( EduUser currentUser){
		EduProject eduProject2 =  new EduProject();
		eduProject2.setEduUser(currentUser);
		List<EduProject> projects = eduProjectService.GruopByForEnrollForUserIdNoPage(eduProject2);
		List<EduProject> eduProjects = new ArrayList<>();
		for(EduProject eduProject :projects){
			String isStatus =  endProjectStatus(eduProject,currentUser.getId());
			List<EduCourse> courses = eduCourseService.courseListByEnrollProjectId(eduProject.getId(), currentUser.getId());
			eduProject.setEndStatus(isStatus);
			eduProject.setEduCourseList(courses);
			eduProjects.add(eduProject);
		}
		return eduProjects;
	}
	public String endProjectStatus(EduProject eduProject,String userId){
		EduEnroll eduEnroll2 = new EduEnroll();
		eduEnroll2.setUserid(userId);
		eduEnroll2.setProjectId(eduProject.getId());
		List<EduEnroll> list = eduEnrollService.findList(eduEnroll2);
		boolean isStatus = true;
		int over = 0;
		for(EduEnroll eduEnroll3 :list){
			if(!"1".equals(eduEnroll3.getStatus())){
				isStatus = false;
			}
			if("3".equals(eduEnroll3.getStatus())){
				over++;
			}
		}
		if(isStatus){
			return "1";
		}
		if(over==list.size()){
			return "3";
		}
		return "0";
	}

	@RequiresPermissions("edu:user:eduUser:edit")
	@RequestMapping(value = "save")
	public String save(EduUser eduUser, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, eduUser)){
			return form(eduUser, model);
		}
		if(StringUtils.isNotBlank(eduUser.getId())){
			EduUser eduUser2 = eduUserService.get(eduUser.getId());
			eduUser2.setRealName(eduUser.getRealName());
			eduUser2.setPhone(eduUser.getPhone());
			eduUser2.setIdCard(eduUser.getIdCard());
			eduUser2.setEmail(eduUser.getEmail());
			if(StringUtils.isNotBlank(eduUser.getPassword())){
				eduUser2.setPassword(DigestUtils.md5Hex(eduUser.getPassword()));
			}
			eduUserService.save(eduUser2);
			addMessage(redirectAttributes, "修改用户成功");
			return "redirect:"+Global.getAdminPath()+"/edu/user/eduUser/?repage";
		}
		eduUser.setPassword(DigestUtils.md5Hex(eduUser.getPassword()));
		eduUser.setImage(Constant.USER_DEFAULT_IMAGE);
		eduUser.setCreateDate(new Date());
		eduUserService.save(eduUser);
		addMessage(redirectAttributes, "保存用户成功");
		return "redirect:"+Global.getAdminPath()+"/edu/user/eduUser/?repage";
	}
	
	@RequiresPermissions("edu:user:eduUser:edit")
	@RequestMapping(value = "delete")
	public String delete(EduUser eduUser, RedirectAttributes redirectAttributes) {
		eduUserService.delete(eduUser);
		addMessage(redirectAttributes, "删除用户成功");
		return "redirect:"+Global.getAdminPath()+"/edu/user/eduUser/?repage";
	}
	/***
	 * 验证该手机号是否已经注册
	 * @param eduUser
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "verificationPhone")
	public String verificationPhone(EduUser eduUser,RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		if(StringUtils.isNotBlank(eduUser.getPhone())){
			boolean checkFormat = verifyPhone(eduUser.getPhone());
			if(!checkFormat){
				 baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
				baseResponseMsg.addData("手机号格式不正确。");
				return renderString(response, baseResponseMsg);
			}
		}
		EduUser eduUserByPhone = eduUserService.getByPhone(eduUser);
		 if(eduUserByPhone != null){
			 if(StringUtils.isNotBlank(eduUser.getId())){
				 EduUser eduUser2 = eduUserService.get(eduUser.getId());
				 if(eduUser2.getPhone().equals(eduUserByPhone.getPhone())){
					 baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
						baseResponseMsg.addData("1");
						return renderString(response, baseResponseMsg);
				 }
			 }
			 baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("该手机号已经注册过了。");
			return renderString(response, baseResponseMsg);
		 }
			 
		 baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("1");
		return renderString(response, baseResponseMsg);
	}
	
	
	/***
	 * 验证该身份证是否已经注册
	 * @param eduUser
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "verificationIdCard")
	public String verificationIdCard(EduUser eduUser,RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		if(StringUtils.isNotBlank(eduUser.getIdCard())){
			boolean format = IdNumber.strongVerifyIdNumber(eduUser.getIdCard());
			if(!format){
				 baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
					baseResponseMsg.addData("身份证格式有误");
					return renderString(response, baseResponseMsg);
			}
		}
		EduUser eduUserByIdCard = eduUserService.getByIdCard(eduUser);
		 if(eduUserByIdCard != null){
			 if(StringUtils.isNotBlank(eduUser.getId())){
				 EduUser eduUser2 = eduUserService.get(eduUser.getId());
				 if(eduUser2.getIdCard().equals(eduUserByIdCard.getIdCard())){
					 baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
						baseResponseMsg.addData("1");
						return renderString(response, baseResponseMsg);
				 }
			 }
			 baseResponseMsg = new BaseResponseMsg(new ResponseMsg("1", "error"));
			baseResponseMsg.addData("该身份证已经使用过了");
			return renderString(response, baseResponseMsg);
		 }
		 baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("1");
		return renderString(response, baseResponseMsg);
	}
	
	/***
	 * 导出用户模板
	 * @param eduUser
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("edu:user:eduUser:edit")
	@RequestMapping(value = "downloadTemplate")
	public String downloadTemplate(EduUser eduUser,RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response, Model model){
		try {
			downloadFile(request, response, "学员表导入模板.xlsx");
			return null;
		} catch (FileNotFoundException e) {
			addMessage(redirectAttributes, "学员表导入模板下载失败, 请求的文件不存在！失败信息：" + e.getMessage());
		} catch (Exception e) {
			addMessage(redirectAttributes, "学员表导入模板下载失败！失败信息：" + e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/edu/user/eduUser/?repage";
	}
	
	public Map<String, String> excelEduUserDict(){
		Map<String, String> map=new HashMap<String, String>();
		map.put("realName", "姓名(必填)");
		map.put("idCard", "身份证号(必填)");
		map.put("phone","手机号(必填)");
		map.put("nickname", "用户名");
		map.put("loginName","登录账号");
		map.put("email", "邮箱");
		map.put("sex", "性别");
		map.put("birth", "生日");
		map.put("haveJobTitle","是否拥有职称");
		map.put("jobTitleName","职称名称");
		map.put("jobTitleLevel", "职称等级");
		map.put("educationLevel", "学历");
		map.put("graduateCollege","毕业院校");
		map.put("major","所学专业");
		map.put("companyName","工作单位");
		map.put("companyNature", "单位性质");
		map.put("isShanghaiFamilyRegister", "是否是上海户籍");
		map.put("createDate", "注册时间");
		return map;
	}
	
	
	@RequiresPermissions("edu:user:eduUser:edit")
	@RequestMapping(value = "export")
	public String export(EduUser eduUser,RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response, Model model){
		try {
			String[] values={"realName","idCard","phone","nickname","loginName","email","sex","birth","haveJobTitle","jobTitleName","jobTitleLevel","educationLevel","graduateCollege","major","companyName","companyNature","isShanghaiFamilyRegister","createDate"};
			List headers = new ArrayList();
			Map eduUserDict = excelEduUserDict();
			Iterator it = eduUserDict.keySet().iterator();
			for (String value : values) {
				headers.add(eduUserDict.get(value));
			}
			List<EduUser> list = eduUserService.findList(eduUser); 
			List<EduUser> eduUsers = new ArrayList<>();
			for(EduUser user :list){
				EduUser eduUser2 =  getEduUserForExtra(user);
				eduUsers.add(eduUser2);
			}
			String fileName = "用户列表"+new Date().getTime()+".xlsx";
			ExportExcel exportExcel = new ExportExcel("用户列表",  headers);
			for(EduUser user : eduUsers){
				Row row = exportExcel.addRow();
				for(int j=0;j<values.length;j++){
					if("realName".equals(values[j])){
						exportExcel.addCell(row, j, user.getRealName());
					}
					if("idCard".equals(values[j])){
						exportExcel.addCell(row, j, user.getIdCard());
					}
					if("phone".equals(values[j])){
						exportExcel.addCell(row, j, user.getPhone());
					}
					if("nickname".equals(values[j])){
						exportExcel.addCell(row, j, user.getNickname());
					}
					if("loginName".equals(values[j])){
						exportExcel.addCell(row,j, user.getLoginName());
					}
					if("email".equals(values[j])){
						exportExcel.addCell(row, j, user.getEmail());
					}
					if("sex".equals(values[j])){
						exportExcel.addCell(row, j,user.getSex());
					}
					if("birth".equals(values[j])){
						if(user.getBirth() != null){
							SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
						    String dateString = formatter.format(user.getBirth());  
							exportExcel.addCell(row, j, dateString);
						}else{
							exportExcel.addCell(row, j, user.getBirth());
						}
						
					}
					if("haveJobTitle".equals(values[j])){
						exportExcel.addCell(row, j, user.getHaveJobTitle());
					}
					if("jobTitleName".equals(values[j])){
						exportExcel.addCell(row,j, user.getJobTitleName());
					}
					if("jobTitleLevel".equals(values[j])){
						exportExcel.addCell(row,j, user.getJobTitleLevel());
					}
					if("educationLevel".equals(values[j])){
						exportExcel.addCell(row,j, user.getEducationLevel());
					}
					if("graduateCollege".equals(values[j])){
						exportExcel.addCell(row,j, user.getGraduateCollege());
					}
					if("major".equals(values[j])){
						exportExcel.addCell(row, j, user.getMajor());
					}
					if("companyName".equals(values[j])){
						exportExcel.addCell(row,j, user.getCompanyName());
					}
					if("companyNature".equals(values[j])){
						exportExcel.addCell(row, j, user.getCompanyNature());
					}
					if("isShanghaiFamilyRegister".equals(values[j])){
						exportExcel.addCell(row, j,user.getIsShanghaiFamilyRegister());
					}
					if("createDate".equals(values[j])){
						exportExcel.addCell(row,j, user.getCreateDate());
					}
				}
			}

//				exportExcel.setDataList(eduUsers);
				exportExcel.write(response, fileName);
				exportExcel.dispose();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	/***
	 * 导入模板
	 * @param eduUser
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("edu:user:eduUser:edit")
	@RequestMapping(value = "importExcel")
	public String importExcel(MultipartFile file,RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response, Model model){
		StringBuffer message = new StringBuffer();
		StringBuffer userIds = new StringBuffer(); 
		BaseResponseMsg baseResponseMsg;
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuffer failureMsg = new StringBuffer();
			ImportExcel ei = new ImportExcel(file,1,0);
			List<EduUser> list = ei.getDataList(EduUser.class);
			for(EduUser eduUser :list){
				 try{  
					 EduUser eduUserByPhone = eduUserService.getByPhone(eduUser);
					 EduUser eduUserByIdCard = eduUserService.getByIdCard(eduUser);
					 if(eduUserByPhone != null){
			                failureNum++;  
			                message.append("姓名为"+eduUser.getRealName()+"手机号为"+eduUser.getPhone()+"的用户的手机号已经注册过了<br/>");
					 }else if(eduUserByIdCard != null){
						 failureNum++;  
			                message.append("姓名为"+eduUser.getRealName()+"手机号为"+eduUser.getPhone()+"的用户的身份证已经注册过了<br/>");
					 }else if(eduUserByPhone == null && eduUserByIdCard ==null){
						 if(!verifyPhone(eduUser.getPhone())){
				                failureNum++;  
							 message.append("姓名为"+eduUser.getRealName()+"手机号为"+eduUser.getPhone()+"的用户的手机号格式错误<br/>");
						 }
						if(!IdNumber.strongVerifyIdNumber(eduUser.getIdCard())){
			                failureNum++;  
							 message.append("姓名为"+eduUser.getRealName()+"手机号为"+eduUser.getPhone()+"的用户的身份证号格式错误<br/>");
						}else{
							 eduUser.setPassword(DigestUtils.md5Hex("12345678"));
							 eduUser.setUserType(Constant.USER_TYPE_IMPORT);//标记为导入用户
							 eduUser.setCreateDate(new Date());
							 eduUserService.save(eduUser);
							 //用户额外信息
							 EduUserExtra eduUserExtra = new EduUserExtra();
							 eduUserExtra.setUserId(eduUser.getId());
							 eduUserExtra.setHaveJobTitle(eduUser.getHaveJobTitle());
							 eduUserExtra.setJobTitleName(eduUser.getJobTitleName());
							 eduUserExtra.setJobTitleLevel(eduUser.getJobTitleLevel());
							 eduUserExtra.setEducationLevel(eduUserExtra.getEducationLevel());
							 eduUserExtra.setGraduateCollege(eduUser.getGraduateCollege());
							 eduUserExtra.setMajor(eduUser.getMajor());
							 eduUserExtra.setCompanyName(eduUser.getCompanyName());
							 eduUserExtra.setCompanyNature(eduUser.getCompanyNature());
							 eduUserExtra.setIsShanghaiFamilyRegister(eduUser.getIsShanghaiFamilyRegister());
							 eduUserExtraService.save(eduUserExtra);
							 userIds.append(eduUser.getId()+",");
							 successNum++;
						}
						
					 }
				 }catch(ConstraintViolationException ex){  
						logger.debug("错误"+ex.getMessage());
		                failureNum++;  
		            }catch (Exception ex) {  
		                failureNum++;  
		            	logger.debug("错误"+ex.getMessage());
		            }  
			}
			if(failureNum>0){
	            failureMsg.insert(0, "，失败 "+failureNum+" 条用户信息。");  
			}
	        addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户信息"+failureMsg);  
		} catch (Exception e) {
	        addMessage(redirectAttributes, "用户信息失败！失败信息："+e.getMessage());  
			logger.debug("错误"+e.getMessage());
		}
		String messageList = message.toString();
		String userIdList = userIds.toString();
		Map map = new HashMap<>();
		map.put("messageList", messageList);
		map.put("userIdList", userIdList);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(map);
		return renderString(response, baseResponseMsg);
	}
	
	
	/***
	 * 验证手机号格式
	 * @param phone
	 * @return
	 */
	public  boolean verifyPhone(String phone){
        String regExp = "^1(3|4|5|7|8)\\d{9}$";  
        if(phone.length() != 11){
        	return false;
        }else{
            Pattern p = Pattern.compile(regExp);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            if(isMatch){
            	return true;
            } else {
            	return false;
            }
        }
	}
	
	/***
	 * 批量报名—课程
	 * @param list
	 * @return
	 */
	@RequestMapping(value = "batchEnroll")
	@ResponseBody
	public String batchEnrollForCourse(@RequestBody EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model){
//		String listJson = request.getParameter("list");
		List<EduOrder> list = eduUser.getList();
		for(EduOrder eduOrder :list){
			eduOrder.setTradeNo(MakeOrderNum.makeOrderNum(Constant.ORDER_TRADENO_DEFAULT));
			
			eduOrder.setPayMethod(Constant.ORDER_PAYMETHOD_OFFLINE);
			eduOrder.setPayStatus(Constant.ORDER_PAYSTATUS_ALREADYPAY);
			eduOrder.setOrderStatus(Constant.ORDER_STATUS_COMPLETED);
			eduOrder.setCreateDate(new Date());
			eduOrderService.save(eduOrder);
			//生成报名详情
			addEnrollDetails(eduOrder);
			List<EduEnroll> list2 = eduOrder.getList();
			List<EduEnroll> eduEnrolls = new ArrayList<>();
			for(EduEnroll eduEnroll :list2){
				//如果不为空，则是项目，则需要查出项目下的课程保存下来。
				if(StringUtils.isNotBlank(eduEnroll.getProjectId())){	
					List<EduCourse> courses = eduCourseService.findProjectContentCourse(eduEnroll.getProjectId());
					for(EduCourse course :courses){
						EduEnroll eduEnroll2 = new EduEnroll();
						eduEnroll2.setUserid(eduEnroll.getUserid());
						eduEnroll2.setCurriculumId(course.getId());
						eduEnroll2.setProjectId(eduEnroll.getProjectId());
						eduEnroll2.setOrderId(eduOrder.getId());
						eduEnroll2.setStatus(Constant.ENROLL_BINDSTATUS_NOT);
						EduEnroll eduEnroll3 = eduEnrollService.getEduEnrollByUserIdAndCourseId(eduEnroll2);
						if(eduEnroll3 ==null){
							eduEnrolls.add(eduEnroll2);
						}
					}
				}else{
					eduEnroll.setOrderId(eduOrder.getId());
					eduEnroll.setStatus(Constant.ENROLL_BINDSTATUS_NOT);
					EduEnroll eduEnroll2 = eduEnrollService.getEduEnrollByUserIdAndCourseId(eduEnroll);
					if(eduEnroll2 ==null){
						eduEnrolls.add(eduEnroll);
					}
				}
			}
			if(eduEnrolls.size()>0){
				eduEnrollService.saveList(eduEnrolls);
			}
		}
		String messageList = "报名成功";
		EduUser eduUser2 = new EduUser();
		Page<EduUser> page = eduUserService.findPage(new Page<EduUser>(request, response), eduUser2); 
		model.addAttribute("messageList", messageList);
		model.addAttribute("page",page);
		return "modules/edu/user/eduUserList";
	}
	/***
	 * 批量报名—项目
	 * @param list
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "batchEnrollForProject")
	@ResponseBody
	public String batchEnrollForProject(@RequestBody EduUser eduUser,HttpServletRequest request, HttpServletResponse response, Model model){
		List<EduOrder> list = eduUser.getList();
		for(EduOrder eduOrder :list){
			eduOrder.setTradeNo(MakeOrderNum.makeOrderNum("O"));
			eduOrder.setPayMethod(Constant.ORDER_PAYMETHOD_OFFLINE);
			eduOrder.setPayStatus(Constant.ORDER_PAYSTATUS_ALREADYPAY);
			eduOrder.setOrderStatus(Constant.ORDER_STATUS_COMPLETED);
			eduOrder.setCreateDate(new Date());
			eduOrderService.save(eduOrder);
			//生成报名详情
			addEnrollDetails(eduOrder);
			List<EduEnroll> list2 = eduOrder.getList();
			List<EduEnroll> eduEnrolls = new ArrayList<>();
			for(EduEnroll eduEnroll :list2){
				List<EduCourse> eduCourses = eduCourseService.findProjectContentCourse(eduEnroll.getProjectId());
				for(EduCourse course :eduCourses){
					EduEnroll eduEnroll2 = new EduEnroll();
					eduEnroll2.setCurriculumId(course.getId());
					eduEnroll2.setOrderId(eduOrder.getId());
					eduEnroll2.setStatus(Constant.ENROLL_BINDSTATUS_NOT);
					//eduEnroll2.setCurriculumName(course.getName());
					eduEnroll2.setUserid(eduOrder.getUserid());
					eduEnroll2.setProjectId(eduEnroll.getProjectId());
					//eduEnroll2.setProjectName(eduEnroll.getProjectName());
					eduEnrolls.add(eduEnroll2);
				}
			}
			eduEnrollService.saveList(eduEnrolls);
		}
		String messageList = "报名成功";
		EduUser eduUser2 = new EduUser();
		Page<EduUser> page = eduUserService.findPage(new Page<EduUser>(request, response), eduUser2); 
		model.addAttribute("messageList", messageList);
		model.addAttribute("page",page);
		return "modules/edu/user/eduUserList";
	}
	
	/***
	 * 生成报名详情
	 * @param eduOrder
	 * @return
	 */
	public void addEnrollDetails(EduOrder eduOrder){
		EduUserExtra eduUserExtra =  eduUserExtraService.getByUserId(eduOrder.getUserid());
		if(eduUserExtra != null){
			EduEnrollDetails details = new EduEnrollDetails();
			details.setOrderId(eduOrder.getId());
			details.setHaveJobTitle(eduUserExtra.getHaveJobTitle());
			details.setJobTitleName(eduUserExtra.getJobTitleName());
			details.setJobTitleLevel(eduUserExtra.getJobTitleLevel());
			details.setEducationLevel(eduUserExtra.getEducationLevel());
			details.setGraduateCollege(eduUserExtra.getGraduateCollege());
			details.setMajor(eduUserExtra.getMajor());
			details.setCompanyName(eduUserExtra.getCompanyName());
			details.setCompanyNature(eduUserExtra.getCompanyNature());
			details.setIsShanghaiFamilyRegister(eduUserExtra.getIsShanghaiFamilyRegister());
			eduEnrollDetailsService.save(details);
		}
		
	}
	
	/***
	 * 将用户的详情页get进user对象里
	 * @return
	 */
	public EduUser getEduUserForExtra(EduUser eduUser){
		EduUserExtra eduUserExtra = eduUserExtraService.getByUserId(eduUser.getId());
		if(eduUserExtra != null){
			eduUser.setHaveJobTitle(eduUserExtra.getHaveJobTitle());
			eduUser.setJobTitleName(eduUserExtra.getJobTitleName());
			eduUser.setJobTitleLevel(eduUserExtra.getJobTitleLevel());
			eduUser.setEducationLevel(eduUserExtra.getEducationLevel());
			eduUser.setGraduateCollege(eduUserExtra.getGraduateCollege());
			eduUser.setMajor(eduUserExtra.getMajor());
			eduUser.setCompanyName(eduUserExtra.getCompanyName());
			eduUser.setCompanyNature(eduUserExtra.getCompanyNature());
			eduUser.setIsShanghaiFamilyRegister(eduUserExtra.getIsShanghaiFamilyRegister());
		}
		return eduUser;
	}
	
	
	
	@RequestMapping(value = "formBatchRegistrationJsp")
	public String formBatchRegistrationJsp(EduCourse educourse, Model model, HttpServletRequest request, HttpServletResponse response,RedirectAttributes redirectAttributes){
		List<EduCourse> list = eduCourseService.findList(educourse);
		model.addAttribute("list",list);
		return "modules/edu/user/eduBatchRegistration";
	}
	
	
	/**
     * 下载指定的模板文件
     * @param request
     * @param response
     * @param fileName
     * @throws ServletException
     * @throws IOException
     */
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, String fileName) 
			throws ServletException, IOException {
        File file = new File(Global.getUserfilesBaseDir() + Global.TEMPLATE_FILES_BASE_URL + fileName);
		int fleng = (int) file.length();
		byte[] content = new byte[fleng];
		// 将文件读入内存
		FileInputStream in = new FileInputStream(file);
		in.read(content);
		in.close();
		// 设置响应类型为文件
		response.setContentType("application/octet-stream; charset=gb2312");
		response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("GBK"),"ISO8859_1"));
		response.setContentLength(content.length);
		// 写入文件内容
		response.getOutputStream().write(content);
		response.flushBuffer();
	}
    
	@RequestMapping(value = "courseAndProjectList")
    public String courseAndProjectList(HttpServletRequest request, HttpServletResponse response, String fileName){
		BaseResponseMsg baseResponseMsg;
		EduCourse educourse = new EduCourse();
		educourse.setOpen(Constant.COURSE_OPEN_YES);
		educourse.setStatus(Constant.COURSE_STATUS_YES);
		educourse.setStudyEndTime(new Date());
		List<EduCourse> courseList = eduCourseService.findList(educourse);
		EduProject eduProject = new EduProject();
		eduProject.setOpen("1");
		List<EduProject> projectList = eduProjectService.findList(eduProject);
		Map map = new HashMap<>();
		map.put("courseList", courseList);
		map.put("projectList", projectList);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(map);
		return renderString(response, baseResponseMsg);
    }
	
	@RequestMapping(value = "unbind")
	public String unbind(HttpServletRequest request, HttpServletResponse response){
		BaseResponseMsg baseResponseMsg;
		String courseId = request.getParameter("id");
		String userId = request.getParameter("userId");
		String projectId = request.getParameter("projectId");
		if(StringUtils.isNotBlank(projectId)){
			List<EduEnroll> eduEnrolls = eduEnrollService.findEnrollByUserIdAndProjectId(projectId, userId);
			for(EduEnroll eduEnroll :eduEnrolls){
				eduEnroll.setStatus("3");
				eduEnrollService.save(eduEnroll);
			}
		}else{
			EduEnroll eduEnroll = eduEnrollService.findEnrollByUserIdAndCourseId(courseId, userId);
			eduEnroll.setStatus("3");
			eduEnrollService.save(eduEnroll);
		}
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData("解绑成功");
		return renderString(response, baseResponseMsg);
	}
	
	@RequestMapping(value = "label")
	public String label( Model model, HttpServletRequest request, HttpServletResponse response,RedirectAttributes redirectAttributes){
		return "modules/edu/user/eduLabel";
	}
	
	
}